package com.xy.cloud.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xy.cloud.domain.dto.UserAddMoneyDTO;
import com.xy.cloud.domain.entities.UserAccount;
import com.xy.cloud.mapper.UserAccountMapper;
import com.xy.cloud.service.UserAccountService;
import io.seata.core.context.RootContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

@Service
public class UserAccountServiceImpl extends ServiceImpl<UserAccountMapper, UserAccount> implements UserAccountService {
    private static final Logger log = LoggerFactory.getLogger(UserAccountServiceImpl.class);


    /**
     * 基于RocketMq的分布式事务  最终一致性
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void increaseAmount(UserAddMoneyDTO userAddMoneyDTO) {
        UserAccount userAccount = this.lambdaQuery().eq(UserAccount::getUserCode, userAddMoneyDTO.getUserCode()).one();
        this.lambdaUpdate().set(UserAccount::getAmount, userAccount.getAmount().add(userAddMoneyDTO.getAmount())).eq(UserAccount::getUserCode, userAddMoneyDTO.getUserCode()).update();
        log.info("================ +" + userAddMoneyDTO.getAmount());
    }

    /**
     * 基于seata的AT模式的分布式事务  强一直性
     */
    @Override
    public void save() {
        String xid = RootContext.getXID();
        log.info("XID: {}",xid);
        UserAccount account = new UserAccount();
        account.setAmount(new BigDecimal("10000"));
        account.setUserCode("002");
        this.save(account);
        int i = 0/1;
        int ii = 1/0;
    }
}
